package select_sort

import "learning/gooop/sorting"

type tSelectSorter struct {
}

func newSelectSorter() sorting.ISorter {
	return &tSelectSorter{}
}

// 选择排序
func (me *tSelectSorter) Sort(data []interface{}, comparator sorting.CompareFunction) []interface{} {
	if data == nil {
		return nil
	}

	size := len(data)
	if size <= 1 {
		return data
	}

	last := size - 1
	for i := 0;i < last;i++ {
		p := me.min(data, i, size, comparator)
		if p != i {
			data[i], data[p] = data[p], data[i]
		}
	}

	return data
}

// 使用线性查找法, 获取最小值的索引
func (me *tSelectSorter) min(data []interface{}, from int, to int, comparator sorting.CompareFunction) int {
	p := from
	v := data[from]

	for i := from + 1;i < to;i++ {
		v1 := data[i]
		if comparator(v1, v) == sorting.LESS {
			p = i
			v = v1
		}
	}

	return p
}

var SelectSorter = newSelectSorter()